import sys

class Domain:
    """
    Contains dictionaries of elements and nodes which describe
    the problem domain.
    """
    from node import Node

    def __init__(self):
        self.current_time = 0.0
        
        self.elements = {}
        self.nodes = {}
        self.sp_constraints = {}
        self.number_of_sp_constraints = 0

        self.has_domain_changed = False
        
    def add_element(self, element, check=False):
        if check:
            for node in element.element_nodes:
                if not node.node_id in self.nodes:
                    print >> sys.stderr, "Error: cannot add element"
                    print >> sys.stderr, "Node " + str(node.node_id) + " is not in this domain"               
                    return False
            
        self.elements[element.element_id] = element
        return True
    
    def add_node(self, node):
        self.nodes[node.node_id] = node

    def add_sp_constraint(self, sp_constraint, check=False):
        if check:
            if not sp_constraint.node.node_id in self.nodes:
                print >> sys.stderr, "Error: cannot add sp_constraint"
                print >> sys.stderr, "Node " + str(sp_constraint.node.node_id) + " is not in this domain"
                return False
        self.sp_constraints[sp_constraint.node.node_id] = sp_constraint
        return True

    def draw_nodes(self):
        from matplotlib.pyplot import plot, savefig, figure
        x = []
        y = []
        for node_id in self.nodes:
            x.append(self.nodes[node_id].coordinates[0])
            y.append(self.nodes[node_id].coordinates[1])
        plot(x,y,'o')
        savefig('nodes.png')

    def remove_element(self, element_id):
        if element_id in self.elements:
            del self.elements[element_id]
        else:
            print "Error: Cannot remove element " + str(element_id) + " from domain."
            print "This element does not exist."

    def remove_node(self, node_id):
        if node_id in self.nodes:
            del self.nodes[node_id]
        else:
            print "Error: Cannot remove node " + str(node_id) + " from domain."
            print "This node does not exist."

if __name__ == "__main__":
    ## from node import *
    ## d = Domain()

    ## from numpy import linspace, array
    ## x = linspace(0.0,1.0, 10)

    ## for n in range(x.size):
    ##     d.add_node(Node(n, coordinates=array([x[n],0.0])))    
    ##     print d.nodes[n].coordinates[0]
    ##     d.draw_nodes()
    ##     print d.nodes.items()
    ##     d.remove_node(0)
    ##     print d.nodes.items()
